package com.puzzlebazar.client.util;

import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.HasAllKeyHandlers;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DeferredCommand;

public abstract class InstantChangeHandler implements ChangeHandler, KeyDownHandler, KeyPressHandler, KeyUpHandler {

	private boolean processed = false;

	private final Command command = new Command(){
		@Override
		public void execute() {  processed = false; onChange(null); } 
	};

	private void process() {
		if( processed ) return;
		processed = true;
		DeferredCommand.addCommand( command );
	}
	
	@Override
	public void onKeyDown(KeyDownEvent event) {
		process();
	}

	@Override
	public void onKeyPress(KeyPressEvent event) {
		process();
	}

	@Override
	public void onKeyUp(KeyUpEvent event) {
		process();
	}

	public void addToWidget( HasAllKeyHandlers widget ) {
		widget.addKeyDownHandler( this );
		widget.addKeyPressHandler( this );
		widget.addKeyUpHandler( this );
	}
	
}
